<?php
namespace Modules\Comment\Controllers;

use Core\Mvc\Controller;
use MongoDB\BSON\ObjectID;
use Core\Paginator\Adapter\Collection as CollectionPaginator;
use Phalcon\Validation;

class IndexController extends Controller
{
    public function indexAction($nid, $page)
    {
        $node = $this->entityManager->get('node', [
            '_id' => new ObjectID($nid)
        ]);
        if(!$node){
            return $this->notFount();
        }

        $commentConfig = $this->config->get('m.comment.config');

        $query = [
            'conditions' => [
                'nid' => $nid,
                'pid' => '0'
            ],
            'sort' => [
                'changed' => -1
            ],
            'limit' => $commentConfig['comment_number'],
            'skip' => 0
        ];
        $noComment = '还没有评论，快来抢占沙发吧～';

        $commentConfig = $this->config->get('m.comment.config');
        $roles = $this->user->getRoles();
        if ($commentConfig['open_comment'] && array_intersect($commentConfig['open_comment'], $roles)) {
            $nodeField = $node->getField();
            $commentEntity = $this->entityManager->get('comment');
            if (isset($nodeField['commentContentModel']) && is_string($nodeField['commentContentModel'])) {
                if (isset($nodeField['commentContentModel']) && $commentEntity instanceof \Core\Mvc\Entity\EntityInterface) {

                    $field = $commentEntity->setContentModel($nodeField['commentContentModel'])->getField();
                    $field['_action'] = $this->url->get(['for' => 'commentSubmit'], ['nid' => $nid, 'pid' => 0]);
                    $field['_form']['pid'] = 0;
                    $field['_form']['id'] = 'main-comment-form';
                    $commentForm = $commentEntity->setContentModel($nodeField['commentContentModel'])->setField($field)->addForm();
                } else {
                    $commentForm = false;
                }
            } else {
                $commentForm = false;
            }
        } else {
            $noComment = '还没有评论，快登录后抢占沙发吧～';
            $commentForm = false;
        }

        $data = $this->entityManager->find('comment', $query);

        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => '\Modules\Comment\Entity\Comment'
        ]);
        self::$variables += array(
            '#templates' => 'pageComment',
            'title' => $node->getTitle().' 的评论',
            'keywords' => $node->getTitle(),
            'description' => $node->getTitle().' 的评论',
            'node' => $node,
            'noComment' => $noComment,
            'commentForm' => $commentForm ? $commentForm->renderForm('comment') : false,
            'data' => $dataPagination->getPaginate(),
        );
    }

    public function submitAction()
    {
        $commentConfig = $this->config->get('m.comment.config');
        //检测是否有权限评论
        $roles = $this->user->getRoles();
        if (!$commentConfig['open_comment'] || !array_intersect($commentConfig['open_comment'], $roles)) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '没有评论的权限'
                ]
            ];
        }

        //评论时间间隔检测
        if (isset($commentConfig['interval']) && $this->session->has('commentTime')) {
            $commentConfig['interval'] = intval($commentConfig['interval']);
            $commentTime = (int)$this->session->get('commentTime');
            $oldTime = $commentTime + $commentConfig['interval'];
            if ($oldTime > intval(time())) {
                $interval = ($commentTime + $commentConfig['interval']) - time();
                return self::$variables = [
                    '#templates' => 'json',
                    'data' => [
                        'state' => false,
                        'notice' => '评论失败，请' . $interval . '秒后发表评论',
                    ]
                ];
            }
        }

        if ($this->request->hasQuery('nid') === false || $this->request->hasQuery('pid') === false) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '评论失败，参数不完整'
                ]
            ];
        }

        $nid = $this->request->getQuery('nid');
        $pid = $this->request->getQuery('pid');

        $validation = new Validation();
        $validation->add('nid', new Validation\Validator\Regex([
            'pattern' => '/([a-z0-9]{24}|0)/',
            'message' => '不是合法的文章Id',
        ]));
        $validation->add('pid', new Validation\Validator\Regex([
            'pattern' => '/([a-z0-9]{24}|0)/',
            'message' => '不是合法的文章Id',
        ]));
        $validationMessages = $validation->validate(['nid' => $nid, 'pid' => $pid]);
        if (count($validationMessages)) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '评论失败，参数不合法'
                ]
            ];
        }

        $nodeEntity = $this->entityManager->get('node', [
            '_id' => new ObjectID($nid)
        ]);
        if (!$nodeEntity) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '评论失败，文章不存在'
                ]
            ];
        }
        if(strlen($pid) == 24) {
            $ParentComment = $this->entityManager->get('comment', [
                '_id' => new ObjectID($pid)
            ]);
            if (!$ParentComment) {
                $pid = '0';
            }
        }else{
            $pid = '0';
        }

        $commentEntity = $this->entityManager->get('comment');
        $nodeField = $nodeEntity->getField();
        $commentContentModel = $this->entityManager->contentModel('comment');
        if (!isset($commentContentModel[$nodeField['commentContentModel']])) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '评论失败，模型' . $commentContentModel . '不存在'
                ]
            ];
        }

        $commentEntity->pid = $pid;
        $commentEntity->nid = $nid;
        $commentEntity->nodeContentModel = $nodeEntity->contentModel ;
        $field = $commentEntity->setContentModel($nodeField['commentContentModel'])->getField();
        $field['_action'] = $this->url->get(['for' => 'commentSubmit'], ['nid' => $nid, 'pid' => $pid]);
        $field['_form']['pid'] = $pid;
        $commentForm = $commentEntity->setContentModel($nodeField['commentContentModel'])->setField($field)->addForm();

        if ($commentEntity->getSaveState() === true) {
            $this->session->set('commentTime',time());
            return self::$variables = [
                '#templates' => 'commentSubmitSuccess',
                'data' => $commentEntity
            ];
        } elseif ($commentEntity->getSaveState() === false) {
            return self::$variables = [
                '#templates' => 'json',
                'data' => [
                    'state' => false,
                    'notice' => '评论失败，模型' . $commentContentModel . '不存在'
                ]
            ];
        } else {
            return self::$variables = [
                '#templates' => 'commentSubmitForm',
                'data' => $commentForm->renderForm('comment')
            ];
        }
    }

    public function loveAction($type, $id)
    {
        $data = array();
        self::$variables += array(
            '#templates' => 'json',
            'data' => &$data,
        );
        $commentEntity = $this->entityManager->get('comment', [
            '_id' => new ObjectID($id)
        ]);
        if (!$commentEntity) {
            return $this->notFount();
        }


        if ($type) {
            $commentEntity->love += 1;
        } else {
            $commentEntity->love -= 1;
        }
        if ($commentEntity->save()) {
            $data = array(
                'state' => 'success',
                'number' => $commentEntity->love,
            );
        } else {
            $data = array(
                'state' => 'flase',
                'number' => $commentEntity->love,
                'notice' => '保存失败',
            );
        }
    }
}
